package dao

import (
	"osiris/core/conversion"
	"osiris/db"
	"osiris/dto"
	"osiris/logger"
	"osiris/model"
	"fmt"
)

func GetTxByHash(hash string) (model.TxModel, error) {
	var txModel model.TxModel
	err := db.MySQL.Where("txHash = ?", hash).First(&txModel).Error
	return txModel, err
}

func GetAllTxs() ([]model.TxModel, error) {
	var txModels []model.TxModel
	err := db.MySQL.Find(&txModels).Error
	return txModels, err
}

func AddTx(txModel model.TxModel) error {
	err := db.MySQL.Create(&txModel).Error
	if err != nil {
		logger.Error(map[string]interface{}{"[dao] [Add tx by model]": err})
		return err
	}

	logger.Info(map[string]interface{}{"[dao] [Add tx by model]": "success"})
	return nil
}

func AddTxs(header dto.BlockHeader, txs []dto.TxData) error {
	for _, txData := range txs {
		err4 := AddTx(conversion.TxData2Model(header, txData))
		if err4 != nil {
			logger.Error(map[string]interface{}{"[dao] [Add Txs] dao.AddTx()": err4})
			return err4
		}
	}

	return nil
}

func TruncateTxs() error {
	return db.MySQL.Exec(fmt.Sprintf("truncate %s", model.TxModel{}.TableName())).Error
}

func DeleteTxByHash(hash string) error {
	err := db.MySQL.Delete(&model.TxModel{}, "txHash = ?", hash).Error
	return err
}
